<?php

namespace app\common\server;

use app\MyController;

class Wx extends MyController
{

    private static $wx_appid = null;
    private static $wx_secret = null;
    private static $mch = null;
    private static $key = null;

    public function initialize()
    {
        $weixinpay = getConfig("weixinpay");
        self::$wx_appid = $weixinpay['appid'];
        self::$wx_secret = $weixinpay['appSecret'];
        self::$mch = $weixinpay['mch_id'];
        self::$key = $weixinpay['keys'];
    }

    /**
     * 获取用户openid
     * @param $code
     * @return int|mixed|\think\response\Json
     */
    public function getOpenid($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . self::$wx_appid . "&secret=" . self::$wx_secret . "&js_code=" . $code . "&grant_type=authorization_code";

        $resUserInfo = $this->get_curl_data($url);
        // dd($resUserInfo);
        if (isset($resUserInfo['errcode'])) {
            return $this->renderError('获取用户信息失败');
        }
        $openid = $resUserInfo['openid'];#openid
        return $openid;
    }

    /**
     * 小程序获取手机号
     * @param string $code
     * @return int|mixed|\think\response\Json
     */
    public function getMobile($code = '')
    {
        $access_token = $this->get_access_token();
        $mobile_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;
        $mobile_info = $this->post_curl_data($mobile_url, ['code' => $code]);
        if ($mobile_info['errcode'] == 0) {
            return $mobile_info['phone_info']['phoneNumber'];
        } else {
            return $this->renderError('获取手机号失败,请刷新重试1');
        }

    }


   /**
     * 获得小程序二维码
     * @param string $open_id
     * @param string $param
     */
    public function GetShareCode($param = '', $save_path = '')
    {
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $result = $this->http_post_data($url, $param);
        file_put_contents($save_path, $result);
        return true;
    }


    /**
     * 推送消息
     * @param string $open_id
     * @param string $goods_name
     * @param string $goods_spec
     * @param string $goods_num
     * @return bool
     */
    public function PushOneMsg($open_id = '', $goods_name = '', $balance_payment = 0)
    {

        $template_id = 'gQTGQR6TEWxWL7HNvGoU3FV2ZhGmBqhQbKcitX6WxzA';
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        $page = 'pages/shouye/index';

        $pushKeywords = [
            'thing2' => ['value' => $goods_name,],
            'amount3' => ['value' => $balance_payment],
            'thing4' => ['value' => "请及时支付"],
        ];
        $data = [
            'access_token' => $access_token,
            'touser' => $open_id,
            'template_id' => $template_id,
            'page' => $page,
            'data' => $pushKeywords,
            'miniprogram_state' => 'formal',//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        ];
        $res = $this->post_curl_data($url, $data);
        if (isset($res_access_token['errcode'])) {
            return $this->renderError('获取失败');
        }
        return json_decode($res, true);
    }

    /**
     * 获取access_token
     */
    public function get_access_token()
    {
        #信息
        $access_token_info = getConfig('access_token');
        if ($access_token_info && $access_token_info['access_token_time'] > time()) {
            $access_token = $access_token_info['access_token'];
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . self::$wx_appid . "&secret=" . self::$wx_secret;
            $res_access_token = $this->get_curl_data($url);
            if (isset($res_access_token['errcode'])) {
                return $this->renderError('获取失败');
            }
            $access_token = $res_access_token['access_token'];
            $expires_in = $res_access_token['expires_in'];
            $access_token_time = time() + 3600;
            $data = [
                'access_token' => $access_token,
                'access_token_time' => $access_token_time,
            ];
            setConfig('access_token', $data);
        }
        return $access_token;

    }


    /**
     * @param $url 请求链接
     */
    public function get_curl_data($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $response = curl_exec($ch);
        if ($response) {
            curl_close($ch);
            return json_decode($response, true);
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return ['errcode' => 1];
        }
    }

    /**
     * @param $url 链接
     * @param $data 参数
     * @return mixed
     */
    public function post_curl_data($url, $data)
    {
        $data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)
        ));
        $return_content = curl_exec($ch);
        if ($return_content) {
            curl_close($ch);
            $return_content = json_decode($return_content, true);
            return $return_content;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return ['errcode' => 1];
        }
    }
    
     /**
     * http - post请求
     * @param $url
     * @param $data
     * @return bool|string
     */
    public function http_post_data($url, $data)
    {
        $data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data)
        ));
        $return_content = curl_exec($ch);
        return $return_content;
    }

    public function post_order($openid,$access_token,$order_num,$title='订单发货'){
        $request_url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=".$access_token;
        $param = '{
                    "order_key": {
                        "order_number_type": 1,
                        "mchid":"'.self::$mch.'",
                        "out_trade_no":"'.$order_num.'"
                    },
                    "logistics_type": 4,
                    "delivery_mode": 1,
                    "shipping_list": [
                        {
                            "item_desc": "本单购买商品已发放至[小程序盒柜]"
                        }
                    ],
                    "upload_time": "2023-08-07T17:16:31+08:00",
                    "payer": {
                        "openid":"'.$openid.'"
                    }
                }';
        $res = curlPost($request_url,$param);
        $res = json_decode($res,true);
        if($res['errcode']==0 && $res['errmsg']=='ok'){
            return 1;
        }else{
            return 2;
        }
    }
    
    
    public function post_order_one($openid,$access_token,$order_num,$title='订单发货'){
        $request_url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=".$access_token;
        $param = '{
                    "order_key": {
                        "order_number_type": 1,
                        "mchid":"'.self::$mch.'",
                        "out_trade_no":"'.$order_num.'"
                    },
                    "logistics_type": 4,
                    "delivery_mode": 1,
                    "shipping_list": [
                        {
                            "item_desc": "本单购买商品已发放至[小程序盒柜]"
                        }
                    ],
                    "upload_time": "2023-08-07T17:16:31+08:00",
                    "payer": {
                        "openid":"'.$openid.'"
                    }
                }';
        $res = curlPost($request_url,$param);
        $res = json_decode($res,true);
        if($res['errcode']==0 && $res['errmsg']=='ok'){
            return 1;
        }else{
            return 2;
        }
    }
}
